<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p class="header-title">订单管理</p>
      <i class="fa fa-refresh refresh-btn" @click="refreshOrders" :class="{ 'refreshing': isRefreshing }"></i>
    </header>

    <!-- 商家信息栏 -->
    <div class="business-info" v-if="business">
      <span class="business-name">{{ business.businessName }}</span>
      <span class="order-count">共 {{ orders.length }} 个订单</span>
    </div>

    <!-- 订单状态筛选 -->
    <div class="filter-tabs">
      <div 
        class="tab-item" 
        :class="{ active: currentFilter === 'all' }"
        @click="setFilter('all')"
      >
        全部订单
      </div>
      <div 
        class="tab-item" 
        :class="{ active: currentFilter === 2 }"
        @click="setFilter(2)"
      >
        待接单
      </div>
      <div 
        class="tab-item" 
        :class="{ active: currentFilter === 3 }"
        @click="setFilter(3)"
      >
        制作中
      </div>
      <div 
        class="tab-item" 
        :class="{ active: currentFilter === 4 }"
        @click="setFilter(4)"
      >
        已完成
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="orders-container" v-if="filteredOrders.length > 0">
      <div 
        class="order-card" 
        v-for="order in filteredOrders" 
        :key="order.orderId"
        @click="viewOrderDetail(order)"
      >
        <div class="order-header">
          <div class="order-info">
            <span class="order-id">订单号：{{ order.orderId }}</span>
            <span class="order-date">{{ formatDate(order.orderDate) }}</span>
          </div>
          <div class="order-status" :class="getStatusClass(order.orderState)">
            {{ getStatusText(order.orderState) }}
          </div>
        </div>
        
        <div class="order-content">
          <div class="customer-info">
            <i class="fa fa-user"></i>
            <span>用户ID：{{ order.userId }}</span>
          </div>
          
          <div class="order-items" v-if="order.list && order.list.length > 0">
            <div class="items-summary">
              <span class="item-count">{{ order.list.length }} 个商品</span>
              <span class="first-item">{{ order.list[0].food?.foodName || '商品' }}</span>
              <span v-if="order.list.length > 1" class="more-items">等</span>
            </div>
          </div>
          
          <div class="order-total">
            <span class="total-label">订单金额：</span>
            <span class="total-amount">¥{{ order.orderTotal.toFixed(2) }}</span>
          </div>
        </div>

        <div class="order-actions" v-if="order.orderState === 2 || order.orderState === 3">
          <!-- 待接单状态 -->
          <template v-if="order.orderState === 2">
            <button 
              class="action-btn accept-btn" 
              @click.stop="quickUpdateOrder(order.orderId, 3, '接受订单')"
            >
              接受订单
            </button>
            <button 
              class="action-btn reject-btn" 
              @click.stop="quickUpdateOrder(order.orderId, 0, '拒绝订单')"
            >
              拒绝订单
            </button>
          </template>
          
          <!-- 制作中状态 -->
          <template v-else-if="order.orderState === 3">
            <button 
              class="action-btn delivery-btn" 
              @click.stop="quickUpdateOrder(order.orderId, 4, '完成订单')"
            >
              完成订单
            </button>
          </template>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <i class="fa fa-list-alt"></i>
      <p v-if="currentFilter === 'all'">暂无订单</p>
      <p v-else-if="currentFilter === 2">暂无待接单订单</p>
      <p v-else-if="currentFilter === 3">暂无制作中订单</p>
      <p v-else-if="currentFilter === 4">暂无已完成订单</p>
      <p v-else>暂无相关订单</p>
    </div>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import Footer from "../components/Footer.vue";
import { useRouter } from "vue-router";
import { ref, inject, onMounted, computed } from "vue";
import { getSessionStorage } from "../common.js";

const axios = inject("axios");
const router = useRouter();

const business = ref(null);
const orders = ref([]);
const currentFilter = ref('all');
const loading = ref(false);
const isRefreshing = ref(false); // 新增：刷新状态

// 计算过滤后的订单
const filteredOrders = computed(() => {
  if (currentFilter.value === 'all') {
    return orders.value;
  }
  if (currentFilter.value === 'processing') {
    // 进行中包括制作中(3)
    return orders.value.filter(order => order.orderState === 3);
  }
  return orders.value.filter(order => order.orderState === currentFilter.value);
});

// 返回上一页
const goBack = () => {
  router.push({ path: '/businessManage' });
};

// 设置筛选条件
const setFilter = (filter) => {
  currentFilter.value = filter;
};

// 获取订单状态样式类
const getStatusClass = (status) => {
  return {
    'status-pending': status === 1,
    'status-waiting': status === 2,
    'status-accepted': status === 3,
    'status-completed': status === 4,
    'status-canceled': status === 0,
    'status-rejected': status === 0,  // 改为0
    'status-refund-pending': status === 5,  // 退款审核中
    'status-refunded': status === 6,  // 已退款
  };
};

// 获取订单状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '已取消/已拒绝';  // 合并显示
    case 1: return '待支付';
    case 2: return '待接单';
    case 3: return '制作中';
    case 4: return '已完成';
    case 5: return '申请退款';  // 修改为申请退款
    case 6: return '已退款';  // 添加已退款状态
    default: return '未知状态';
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return dateStr;
  }
};

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push({ 
    path: '/businessOrderDetail', 
    query: { orderId: order.orderId } 
  });
};

// 快速操作订单
const quickUpdateOrder = async (orderId, newStatus, actionText) => {
  if (!confirm(`确定要${actionText}吗？`)) {
    return;
  }
  
  try {
    loading.value = true;
    console.log(`开始${actionText}，订单ID: ${orderId}，目标状态: ${newStatus}`);
    
    const response = await axios.put(`/api/orders/${orderId}/status?status=${newStatus}`);
    console.log(`${actionText}响应:`, response);
    
    // 更全面的响应判断
    if (response) {
      // 直接检查订单对象的id属性
      if (response === 1 || response.success || response.id || (response.data && response.data.id)) {
        alert(`${actionText}成功！`);
        // 更新本地订单状态
        const order = orders.value.find(o => o.orderId === orderId);
        if (order) {
          order.orderState = newStatus;
        }
        // 刷新订单列表
        loadOrders();
      } else {
        console.error(`${actionText}失败，响应不符合预期:`, response);
        alert('操作失败，请重试');
      }
    } else {
      console.error(`${actionText}失败，响应为空`);
      alert('操作失败，服务器无响应');
    }
  } catch (error) {
    console.error(`${actionText}失败:`, error);
    alert(`操作失败: ${error.message || '请检查网络连接'}`);
  } finally {
    loading.value = false;
  }
};

// 刷新订单列表
const refreshOrders = async () => {
  if (!business.value) return;
  if (isRefreshing.value) return; // 防止重复点击

  isRefreshing.value = true;
  try {
    loading.value = true;
    console.log("开始刷新订单...");
    
    const bizId = business.value.id || business.value.businessId;
    const response = await axios.get(`/api/orders/business/${bizId}`);
    console.log("刷新订单API响应:", response);

    let raw = [];
    if (response && Array.isArray(response)) {
      raw = response;
    } else if (response && response.success) {
      raw = Array.isArray(response.data) ? response.data : [];
    }

    orders.value = raw.map(o => ({
      id: o.id,
      orderId: o.id,
      orderDate: o.orderDate,
      orderState: o.orderState,
      orderTotal: typeof o.orderTotal === 'number' ? o.orderTotal : (o.orderTotal?.toString ? parseFloat(o.orderTotal.toString()) : 0),
      userId: o.customer ? o.customer.id : undefined,
      list: [] // 如需展示商品摘要，可后续按需调用 /api/orders/{id}/detailets 填充
    }));
    console.log("成功刷新订单数量:", orders.value.length);
    // 移除成功提示
  } catch (error) {
    console.error("刷新订单失败:", error);
    alert('刷新订单失败，请检查网络连接');
  } finally {
    loading.value = false;
    isRefreshing.value = false;
  }
};

// 页面初始化
onMounted(() => {
  // 检查登录状态（优先 sessionStorage，兼容 localStorage）
  const sessionBiz = getSessionStorage("business");
  const localBizStr = localStorage.getItem("business");
  const localBiz = localBizStr ? JSON.parse(localBizStr) : null;
  const businessInfo = sessionBiz || localBiz;
  if (!businessInfo) {
    alert("请先登录！");
    router.push({ path: '/businessLogin' });
    return;
  }
  
  business.value = businessInfo;
  console.log("当前登录商家:", business.value);
  
  // 加载订单数据
  loadOrders();
});

// 加载商家订单
const loadOrders = async () => {
  if (!business.value) return;
  
  try {
    loading.value = true;
    // 兼容不同字段名，这里统一使用 id
    const bizId = business.value.id || business.value.businessId;
    console.log("正在加载商家订单，商家ID:", bizId);
    
    const response = await axios.get(`/api/orders/business/${bizId}`);
    console.log("订单API响应:", response);
      
      // 适配后端HttpResult包装
      let raw = [];
      if (response && Array.isArray(response)) {
        raw = response;
      } else if (response && response.success) {
        raw = Array.isArray(response.data) ? response.data : [];
      }
      
      // 标准化字段，适配页面使用的结构
      orders.value = raw.map(o => ({
        id: o.id,
        orderId: o.id,
        orderDate: o.orderDate,
        orderState: o.orderState,
        orderTotal: typeof o.orderTotal === 'number' ? o.orderTotal : (o.orderTotal?.toString ? parseFloat(o.orderTotal.toString()) : 0),
        userId: o.customer ? o.customer.id : undefined,
        list: [] // 如需展示商品摘要，可后续按需调用 /api/orders/{id}/detailets 填充
      }));
      
      console.log("成功加载订单数量:", orders.value.length);

  } catch (error) {
    console.error("加载订单失败:", error);
    orders.value = [];
    alert('加载订单失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 14vw;
}

/* header样式 */
header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.5vw;
  
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  
  display: flex;
  justify-content: space-between; /* 可改为: flex-start 或 center，然后使用margin调整 */
  align-items: center;
  padding: 0 4vw;
  
  /* 如果需要更精确地控制子元素位置，可以设置为relative */
  /* position: relative; */
}

header .fa-angle-left {
  font-size: 5vw;
  cursor: pointer;
  width: 5vw;
}

.header-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  /* 如果需要调整标题与按钮的相对位置，可以修改这里的transform */
  /* transform: translateX(-40%); */ /* 向左偏移，为刷新按钮腾出空间 */
}

.placeholder-icon {
  width: 5vw;
  visibility: hidden;
}

/* 商家信息栏 */
.business-info {
  width: 95%; 
  margin: 14vw auto 2vw auto;
  background-color: #fff;
  border-radius: 2vw;
  padding: 3vw 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  box-sizing: border-box; /* 确保padding计入宽度 */
}

.business-name {
  font-size: 4vw;
  font-weight: bold;
  color: #333;
}

.order-count {
  font-size: 3vw;
  color: #0097ff;
}

/* 筛选标签 */
.filter-tabs {
  width: 94%;
  margin: 2vw auto;
  background-color: #fff;
  border-radius: 2vw;
  padding: 1vw;
  display: flex;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 2.5vw 0;
  font-size: 3.2vw;
  color: #666;
  border-radius: 1.5vw;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tab-item.active {
  background-color: #0097ff;
  color: #fff;
}

/* 订单容器 */
.orders-container {
  width: 94%;
  margin: 2vw auto;
}

/* 订单卡片 */
.order-card {
  background-color: #fff;
  border-radius: 2vw;
  margin-bottom: 2vw;
  padding: 3vw;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.order-card:hover {
  transform: translateY(-1px);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 2vw;
  padding-bottom: 2vw;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  flex-direction: column;
}

.order-id {
  font-size: 3.5vw;
  font-weight: bold;
  color: #333;
  margin-bottom: 1vw;
}

.order-date {
  font-size: 2.8vw;
  color: #999;
}

.order-status {
  padding: 1vw 2vw;
  border-radius: 1vw;
  font-size: 2.8vw;
  font-weight: bold;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-accepted {
  background-color: #cce5ff;
  color: #0066cc;
}

.status-delivery {
  background-color: #ffe6cc;
  color: #cc6600;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-rejected {
  background-color: #f8d7da;
  color: #721c24;
}

.status-refund-pending {
  color: #ff9800;
  background-color: #fff3e0;
}

.status-refunded {
  color: #f44336;
  background-color: #ffebee;
}

/* 订单内容 */
.order-content {
  margin-bottom: 2vw;
}

.customer-info {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
  font-size: 3vw;
  color: #666;
}

.customer-info .fa-user {
  margin-right: 2vw;
  color: #0097ff;
}

.order-items {
  margin-bottom: 2vw;
}

.items-summary {
  font-size: 3vw;
  color: #666;
}

.item-count {
  color: #0097ff;
  font-weight: bold;
  margin-right: 1vw;
}

.order-total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.total-label {
  font-size: 3vw;
  color: #666;
  margin-right: 1vw;
}

.total-amount {
  font-size: 4vw;
  font-weight: bold;
  color: #e74c3c;
}

/* 订单操作 */
.order-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 2vw;
  border-top: 1px solid #f0f0f0;
}

.action-btn {
  padding: 2vw 4vw;
  border: none;
  border-radius: 1.5vw;
  font-size: 3vw;
  cursor: pointer;
  transition: all 0.3s ease;
}

.accept-btn {
  background-color: #27ae60;
  color: #fff;
}

.accept-btn:hover {
  background-color: #219a52;
}

.delivery-btn {
  background-color: #f39c12;
  color: #fff;
}

.delivery-btn:hover {
  background-color: #e67e22;
}

.complete-btn {
  background-color: #3498db;
  color: #fff;
}

.complete-btn:hover {
  background-color: #2980b9;
}

/* 空状态 */
.empty-state {
  text-align: center;
  margin-top: 8vw;
  color: #999;
}

.empty-state .fa-list-alt {
  font-size: 12vw;
  margin-bottom: 2vw;
}

.empty-state p {
  font-size: 3.5vw;
}

/* 刷新按钮样式 */
.refresh-btn {
  font-size: 4.5vw;
  cursor: pointer;
  width: 5vw;
  text-align: center;
  color: #fff;
  
  /* 可以调整以下属性来改变按钮位置 */
  margin-right: 10vw; /* 调整右侧间距 */
  /* position: absolute; */ /* 取消注释以使用绝对定位 */
  /*right: 8vw; */ /* 与右边的距离 */
  /* top: 50%; */ /* 垂直居中 */
  /* transform: translateY(-50%); */ /* 垂直居中微调 */
}

.refresh-btn.refreshing {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式适配 */
@media (max-width: 480px) {
  header {
    height: 50px;
    padding: 0 16px;
  }
  
  .business-info {
    margin-top: 60px;
    padding: 12px 16px;
  }
  
  .business-name {
    font-size: 16px;
  }
  
  .order-count {
    font-size: 12px;
  }
  
  .tab-item {
    padding: 10px 0;
    font-size: 13px;
  }
  
  .order-card {
    padding: 12px;
    margin-bottom: 8px;
  }
  
  .order-id {
    font-size: 14px;
  }
  
  .order-date {
    font-size: 11px;
  }
  
  .order-status {
    padding: 4px 8px;
    font-size: 11px;
  }
  
  .customer-info {
    font-size: 12px;
  }
  
  .items-summary {
    font-size: 12px;
  }
  
  .total-label {
    font-size: 12px;
  }
  
  .total-amount {
    font-size: 16px;
  }
  
  .action-btn {
    padding: 8px 16px;
    font-size: 12px;
  }
}
</style> 